package org.amj.wn;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.*;


@SuppressWarnings("serial")
public class AdminServiceOperations extends HttpServlet {

	public static final String CURRENT_USER = "CURRENT_USER";

	enum Operation {
		CREATE, DELETE, MODIFY;

	}

	class OperationInfo {
		private final String memberCode;
		private final String passCode;
		private final Map<String, String> otherValues;
		private final Operation operation;
		private OperationInfo(String memberCode, String passCode,
				Map<String, String> otherValues, Operation operation) {
			super();
			this.memberCode = memberCode;
			this.passCode = passCode;
			this.otherValues = otherValues;
			this.operation = operation;
		}
		public String getMemberCode() {
			return memberCode;
		}
		public String getPassCode() {
			return passCode;
		}
		public Map<String, String> getOtherValues() {
			return otherValues;
		}
		public Operation getOperation() {
			return operation;
		}


	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		
		
		OperationInfo opInfo = getOperationInfo(req);
		
		boolean result = true;
		if(opInfo != null) {
			switch(opInfo.getOperation()) {
			case CREATE:
				result = WaqfeNau.createOrUpdate(opInfo.memberCode, opInfo.passCode, req.getParameter(Property.jamaatCode.name()));
				break;
			case DELETE:
				WaqfeNau.delete(opInfo.memberCode);
				break;
			case MODIFY:
				result = WaqfeNau.modify(opInfo.memberCode, opInfo.getOtherValues());
				break;
			}
		}		
		
		if(result)
			resp.sendRedirect("/admin/menu.jsp?r=2");
		else 
			resp.sendRedirect("/admin/menu.jsp?r=1");
	}

	private OperationInfo getOperationInfo(HttpServletRequest req) {
		String operation = req.getParameter("opt");
		
		Operation opr = null;
		try {
			opr = Operation.valueOf(operation);
		}catch(Exception exp) { return null;}
		
		Property[] properties = Property.values();
		
		Map<String, String> values = new HashMap<String, String>();
		
		for (Property property : properties) {
			if(property.getUiElement() == UIElement.FIELD) {
				if(property != Property.memberCode && property != Property.passCode) {
					String value = req.getParameter(property.toString());
					if(value != null)
						values.put(property.toString(), value);
				}
			}
		}

		return new OperationInfo(getMemberCode(req),
				req.getParameter(Property.passCode.toString()), values, opr);
	}

	private String getMemberCode(HttpServletRequest req) {
		return req.getParameter(Property.memberCode.toString());
	}

}
